import { getToken, setToken, removeToken } from '@/utils/ssoUtils'
import { userById } from '@/api/user'

const state = {
  token: getToken(),
  name: '',
  avatar: '',
  permission: false
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token;
  },
  SET_NAME: (state, name) => {
    state.name = name;
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar;
  },
  SET_PERMISSION: (state, permission) => {
    state.permission = permission;
  }
}

const actions = {
  // user login
  login({ commit }, token) {
    commit('SET_TOKEN', token);
    setToken(token);
  },

  // get user info
  getInfo({ commit, state }, data) {
    return new Promise((resolve, reject) => {
      userById(data)
        .then(res => {
          const { userName, avatar } = res.result
          commit('SET_NAME', userName)
          commit('SET_AVATAR', avatar)
          resolve(res)
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // setPermission
  setPermission({ commit, state }, data) {
    return new Promise((resolve, reject) => {
      commit('SET_PERMISSION', data)
      resolve(data)
    })
  },

  // user logout
  logout({ commit, state }) {
    commit('SET_TOKEN', '')
    removeToken()
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      removeToken()
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
};
